package com.wys.mall.client.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.wys.mall.client.controller
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-07-0713:39
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
@Controller
public class IndexController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 无须登录
     *
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    /**
     * 登录后才能访问
     * 能够感知从ssoserver登录成功
     *
     * @param model
     * @param token 由sso登录成功带回来
     * @return
     */
    @GetMapping("/list")
    public String list(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            if(!StringUtils.isEmpty(body)){
                redisTemplate.opsForValue().set("loginUser", body);
                this.setData(model);
                return "list";
            }else {
                return "redirect:" + ssoServerUrl + "?redirect_url=http://client1.com:8081/list";
            }
        } else {
            Object loginUser = redisTemplate.opsForValue().get("loginUser");
            if (loginUser == null) {
                return "redirect:" + ssoServerUrl + "?redirect_url=http://client1.com:8081/list";
            } else {
                this.setData(model);
                return "list";
            }
        }


    }

    private void setData(Model model) {
        List<String> users = new ArrayList<>();
        users.add("tom1");
        users.add("tom2");
        users.add("tom3");
        users.add("tom4");
        model.addAttribute("users", users);
    }
}
